package com.bonc.ioc.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.bonc.ioc.common.util.AppReply;
import com.bonc.ioc.config.OtherProperties;
import com.bonc.ioc.model.FileUpload;
import com.bonc.ioc.service.FileUploadHistoryService;
import com.bonc.ioc.util.CustomFileUtils;
import com.bonc.ioc.validation.AppAuthAnnotation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author wangqinglin@bonc.com.cn
 * @date 2020/12/10 21:28
 * @change: 2020/12/10 21:28 by wangqinglin@bonc.com.cn for init
 */

@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {

    @Resource
    private OtherProperties otherProperties;

    @Resource
    private FileUploadHistoryService fileUploadHistoryService;

    @Value("${fileType}")
    private String fileType;

    /**
     * 单文件上传
     * 以用户名为子目录区分 不同人上传的相同文件
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @AppAuthAnnotation
    public AppReply singleFileUpload(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return AppReply.error("请上传文件");
        }
//        获取文件或文件夹名称
//        String name = file.getName();
        //原始文件名
        String oldName = file.getOriginalFilename();
        //获取文件长度
        int length = file.getOriginalFilename().length();
        //获取文件名前缀
        String filePrefix = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
        //获取文件名后缀
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), length);
        //限定文件类型
        boolean type = false;
        String regex = ",";
        for (String types : fileType.split(regex)) {
            type = types.equals(fileSuffix);
            if (type) {
                break;
            } else {
                continue;
            }
        }
        if (type) {
            //生成新的文件名
            String newFileName = filePrefix + "_" + System.currentTimeMillis() + "_"  + oldName + fileSuffix;
            //上传文件
//            在方法下添加了try/catch
            CustomFileUtils.uploadSingleFileToPath(file, otherProperties.getUploadPth(), newFileName);
            //记录文件信息
            FileUpload fileUpload = new FileUpload(oldName, newFileName, otherProperties.getUploadPth() + File.separator + newFileName, new Date());
            fileUploadHistoryService.insertFileHistory(fileUpload);
            return new AppReply(AppReply.SUCCESS_CODE, "上传成功", otherProperties.getUploadPth() + File.separator + newFileName);
        } else {
            return new AppReply(AppReply.EORRO_CODE, "不允许该类文件上传！！！", "");
        }

    }

    @SneakyThrows
    @GetMapping("/download")
    @AppAuthAnnotation
    public void getImportExcel(HttpServletResponse response, @RequestParam String path, HttpServletRequest request) {
        File file = new File(path);
        if (file.exists()) {
            CustomFileUtils.downloadSingleFileFromPath(file, response);
        }
    }
    @SneakyThrows
    @PostMapping("/downloadN")
    @AppAuthAnnotation
    public void downloadN(HttpServletResponse response, @RequestParam String path, HttpServletRequest request) {
        int i = path.lastIndexOf("/uploadfile/");
        String newName = path.substring(i+"/uploadfile/".length());
        log.info(newName);
        String filePrefix = newName.substring(0, newName.lastIndexOf("_"));
        String fileSuffix = newName.substring(newName.lastIndexOf("."), newName.length());
        String simpleName = filePrefix + fileSuffix;
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", StrUtil.format("attachment;filename*=utf-8'zh_ch'{}", URLUtil.encode(simpleName, "UTF-8")));
        response.setCharacterEncoding("UTF-8");
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(3 * 1000);
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        InputStream bis = conn.getInputStream();
        ServletUtil.write(response, bis);
    }
}
